/*
 * Copyright (c) 2025 Industrial Software Feature Database
 */
package com.comac.ins.isfd.util;

import com.comac.ins.isfd.domain.vo.IsfdDatabaseTypeManagementVo;
import com.comac.ins.isfd.domain.vo.IsfdMeshModelCollectTreeVo;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class TreeUtils {
    public static IsfdMeshModelCollectTreeVo buildTree(List<IsfdMeshModelCollectTreeVo> list) {
        Map<Long, IsfdMeshModelCollectTreeVo> nodeMap = new HashMap<>();
        List<IsfdMeshModelCollectTreeVo> roots = new ArrayList<>();

        for (IsfdMeshModelCollectTreeVo node : list) {
            nodeMap.put(node.getId(), node);
            node.setChildren(new ArrayList<>());
        }
        for (IsfdMeshModelCollectTreeVo node : list) {
            Long parentId = node.getParentId();
            if (parentId == 0L) {
                roots.add(node);
            } else {
                IsfdMeshModelCollectTreeVo parentNode = nodeMap.get(parentId);
                if (parentNode != null) {
                    parentNode.getChildren().add(node);
                }
            }
        }
        if (!roots.isEmpty()) {
            return roots.get(0);
        } else {
            return null;
        }
    }


    public static List<IsfdDatabaseTypeManagementVo> buildDatabaseTypeTree(List<IsfdDatabaseTypeManagementVo> allNodes) {
        if (CollectionUtils.isEmpty(allNodes)) {
            return new ArrayList<>();
        }
        // map作为字典
        Map<Long, IsfdDatabaseTypeManagementVo> nodeMap = new HashMap<>();
        for (IsfdDatabaseTypeManagementVo node : allNodes) {
            nodeMap.put(node.getId(), node);
        }
        // 封装树
        List<IsfdDatabaseTypeManagementVo> rootNodes = new ArrayList<>();
        for (IsfdDatabaseTypeManagementVo node : allNodes) {
            Long parentId = node.getParentId();
            if (parentId == null || parentId == 0) {
                rootNodes.add(node);
            } else {
                IsfdDatabaseTypeManagementVo parent = nodeMap.get(parentId);
                if (parent != null) {
                    parent.addChild(node);
                }
            }
        }
        return rootNodes;
    }
}
